package com.lgf.view.listener;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.nio.charset.Charset;
import java.util.List;
import java.util.Set;

import com.lgf.entity.CodeFileVo;
import com.lgf.tool.file.CodeNoteHelper;
import com.lgf.vo.CodeFileTypeEnum;

import cn.hutool.core.io.FileUtil;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;

/**
 * 点击后运行处理程序
 * 
 * @author zhouz
 * @date 2019年11月14日
 *
 */
@Slf4j
public class RunBtnClickListener implements ActionListener {
	private Set<String> types;
	private List<CodeFileVo> files;
	@Setter
	private File outDir;
	@Setter
	private File baseDir;

	public void setFiles(List<CodeFileVo> files) {
		this.files = files;
	}

	public void setTypes(Set<String> types) {
		this.types = types;
	}

	@Override
	public void actionPerformed(ActionEvent e) {
		log.info("开始处理");
		for (CodeFileVo file : files) {
			if (file.getFile().isDirectory()) {
				continue;
			}
			if (types.contains(file.getType().getText())) {
				String info = this.removeNote(file);
				String pp = file.getFile().getAbsolutePath();
				int len = this.baseDir.getAbsolutePath().length();
				String dir = pp.substring(len);
				File outFile = new File(this.outDir + File.separator + dir);
				FileUtil.writeUtf8String(info, outFile);
			}
		}
		log.info("处理结束");
	}

	private String removeNote(CodeFileVo codeFile) {
		String info = null;
		codeFile.setSelected(true);
		String content = FileUtil.readString(codeFile.getFile(), Charset.forName("UTF-8"));
		for (String type : types) {
			if (type.equals(CodeFileTypeEnum.HTML.getText())) {
				info = CodeNoteHelper.removeNoteByHtml(content);
			} else if (type.equals(CodeFileTypeEnum.CSS.getText())) {
				info = CodeNoteHelper.removeNoteByCss(content);
			} else if (type.equals(CodeFileTypeEnum.JS.getText())) {
				info = CodeNoteHelper.removeNoteByJs(content);
			} else if (type.equals(CodeFileTypeEnum.PHP.getText())) {
				info = CodeNoteHelper.removeNoteByPhp(content);
			}
		}
		return info;
	}

}
